package cms.simmytech.web.base;

import java.io.OutputStream;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cms.simmytech.config.MyPasswordEncoder;
import cms.simmytech.model.SysUser;
import cms.simmytech.model.TbBase;
import cms.simmytech.service.UserService;
import cms.simmytech.util.EncryUtil;
import cms.simmytech.util.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;


@Component
public abstract class BaseController{

	protected Log log = LogFactory.getLog(BaseController.class);

//	private Stack<String> browseRecord = new Stack<>();

	@Autowired
	private MyPasswordEncoder passowrdEncoder;

	@Autowired
	protected UserService userService;

	@Value("${simmytech.momentPath}")
	protected String webPath;

	@Value("${simmytech.basePath}")
	private String basePath;

	@Value("${simmytech.webSiteName}")
	private String webSiteName;

	private String cookieRedName="_redLog";


	/**
	 * 加密隐藏域数据
	 * 
	 * @param model
	 * @param temps
	 */
	protected void encryption(Model model, Object... temps) {
		String inputStr = getString(temps);
		String password = passowrdEncoder.encode(inputStr);
		model.addAttribute("encryStr", password);
	}

	/**
	 * 匹配隐藏域数据
	 * 
	 * @param encryStr
	 * @param response
	 * @param temps
	 */
	protected void encrytMath(String encryStr, HttpServletResponse response, Object... temps) {
		String inputStr = getString(temps);
		boolean res = passowrdEncoder.matches(inputStr, encryStr);
		if (!res) {
			errorResponse(response);
		}
	}


	private String getString(Object[] temps) {
		StringBuffer sb = new StringBuffer();
		for (Object temp : temps) {
			if (null == temp) {
				continue;
			}
			sb.append(temp);
			sb.append("-");
		}
		return sb.toString();
	}

	private void errorResponse(HttpServletResponse response) {
		try {
			String data = "提交数据错误";
			OutputStream outputStream = response.getOutputStream();
			response.setHeader("content-type", "text/html;charset=UTF-8");
			byte[] dataByteArr = data.getBytes("UTF-8");
			outputStream.write(dataByteArr);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 输出web地址
	 * 
	 * @param model
	 */
	protected void renderWebPath(Model model) {
		model.addAttribute("webPath", webPath);

	}
	protected  String toPage(String path,Model model){
		model.addAttribute("basePath",basePath);
		return path;
	}
	/**
	 * 获取当前当前用户和
	 *
	 */
	protected SysUser getUser() {
		SysUser admin = userService.getUserInfo();
		return admin;
	}
	/**
	 * 获取当前当前用户和
	 *
	 */
	protected TbBase getBase() {
		TbBase base = userService.getBase();
		return base;
	}
	/**
	 * 页面操作记录
	 * @param request
	 */
	protected  void pushRecord(HttpServletRequest request,HttpServletResponse response){
		StringBuilder redUrl=new StringBuilder();
		String redUrl1=getCoolieValue(request);
		if(!StringUtils.isEmpty(redUrl1)){
			String[] temps= redUrl1.split("\\|\\|");
			if(temps.length>=5){
				for(int i=1;i<temps.length;i++){
					redUrl.append(temps[i]).append("||");
				}
			}else {
				redUrl.append(redUrl1).append("||");
			}
		}
		StringBuilder url=new StringBuilder(request.getRequestURI());
		if(!StringUtils.isEmpty(request.getQueryString())){
			url.append("?").append(request.getQueryString());
		}
		redUrl.append(url.toString());
		setCoolieValue(response,redUrl.toString());
	}

	/**
	 * 跳转指定记录页
	 * @param postion
	 * @return
	 */
	protected String toRecord(int postion,HttpServletRequest request) {
		String redUrl=getCoolieValue(request);
		if(!StringUtils.isEmpty(redUrl)){
			String[] res= redUrl.split("\\|\\|");
			String temp="redirect:" + res[res.length-postion].replace(webSiteName,"");
			return temp;
		}
		return "";
	}

	/**
	 * 获取指定记录仪
	 * @param model
	 * @param postion
	 */
	protected void getRecord(Model model, int postion,HttpServletRequest request){
		String redUrl=getCoolieValue(request);
		if(!StringUtils.isEmpty(redUrl)){
			String[] res= redUrl.split("\\|\\|");
			model.addAttribute("returl", res[res.length-postion]);
		}
	}
	private String getCoolieValue(HttpServletRequest request){
		Cookie[] cookies= request.getCookies();
		String redUrl=null;
		if(cookies!=null){
			for (Cookie cookie:cookies){
				if(cookie.getName().equals(cookieRedName)){
					redUrl=EncryUtil.decrypt(cookie.getValue());
				}
			}
		}
		return redUrl;
	}
	private void setCoolieValue(HttpServletResponse response,String v){
		response.addCookie(new Cookie(cookieRedName,EncryUtil.encrypt(v)));
	}
}
